﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Ionic.Zip;
using System.Diagnostics;



namespace NagnagyPrint
{
    public partial class MainForm : Form
    {
        public static string OrdersUrl
        {
            get { return _OrdersUrl; }
            set { _OrdersUrl = value; }

        }
        public static string DownloadPath
        {
            get { return _DownloadPath; }
            set { _DownloadPath = value; }

        }
        public static string OrdersManage
        {
            get { return _OrdersManage; }
            set { _OrdersManage = value; }

        }
        public static int Refreshtime
        {
            get {

                int timetortefresh = Convert.ToInt32(_refreshtime);
                return timetortefresh;
            }
            set { _refreshtime = value.ToString(); }

        }

        
        static string  _OrdersUrl = ConfigurationManager.AppSettings["OrdersUrl"].ToString();
        static string _DownloadPath = ConfigurationManager.AppSettings["DownloadPath"].ToString();
        static string _OrdersManage = ConfigurationManager.AppSettings["OrdersManage"].ToString();
        static string _refreshtime = ConfigurationManager.AppSettings["refreshtime"].ToString();


        
        private BackgroundWorker backgroundWorker1;
        private Order oredrToprint;
        NagnagyOrders CurrentOrders;
        Timer MyTimer;
        private Object thisLock = new Object();
        public MainForm()
        {
            InitializeComponent();
            backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
            backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
    
            listViewThreads.MouseClick += new MouseEventHandler(listViewThreads_MouseClick);

            this.listViewThreads.MouseUp += new MouseEventHandler(listViewThreads_MouseUp);
            //this.TopMost = true;
            //this.FormBorderStyle = FormBorderStyle.None;
            this.FormBorderStyle = FormBorderStyle.FixedToolWindow;

            this.WindowState = FormWindowState.Maximized;
            int timerinterval = Refreshtime;

            MyTimer = new Timer();
            MyTimer.Interval = timerinterval; // 30 second
            MyTimer.Tick += new EventHandler(MyTimer_Tick);
            MyTimer.Start();

            GetOrdersFromServer();
            FillOrderListUI();
        }
        private void MyTimer_Tick(object sender, EventArgs e)
        {
            MyTimer.Stop();
            //MessageBox.Show("The form will now be closed.", "Time Elapsed");
            GetOrdersFromServer();
            FillOrderListUI();
            foreach (Order item in CurrentOrders.orders.order)
            {

                


                oredrToprint = item;
                this.backgroundWorker1.RunWorkerAsync(item.token);
              //  backgroundWorker1_DoWork(item.token);
                while (this.backgroundWorker1.IsBusy)
                {
                    progressBar1.Increment(1);

                    // Keep UI messages moving, so the form remains  
                    // responsive during the asynchronous operation.
                    Application.DoEvents();
                }
                try
                {
                   
                   

                    //    repForm.FormBorderStyle = FormBorderStyle.FixedToolWindow;

                 //  repForm.WindowState = FormWindowState.Normal;
                   // repForm.ShowDialog();


                    MakeRequest_update(oredrToprint.update);
                    ReportByIDAndProject repForm = new ReportByIDAndProject();
                    repForm.order = oredrToprint;
                    repForm.GenerateReportForOrder();
                    GetOrdersFromServer();
                    FillOrderListUI();
                  
                    repForm.Close();
                    MyTimer.Start();
                }
                catch { }
                
                           
                
            }
            

           // this.Close();
        }
        void listViewThreads_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

                //    contextMenuStrip1.Show(listViewThreads, e.Location);
                var hitTestInfo = listViewThreads.HitTest(e.X, e.Y);
                if (hitTestInfo.Item != null)
                {
                    var loc = e.Location;
                    loc.Offset(listViewThreads.Location);

                    // Adjust context menu (or it's contents) based on hitTestInfo details
                    this.contextMenuStrip1.Show(listViewThreads, loc);
                }

            }
        }

        void listViewThreads_MouseClick(object sender, MouseEventArgs e)
        {
           
        }

        private void btnGetNewOrders_Click(object sender, EventArgs e)
        {
            GetOrdersFromServer();
            FillOrderListUI();
        }

        private void FillOrderListUI()
        {
            if(null==CurrentOrders) 
            {
               // MessageBox.Show("There  is no  new orders ");
                return;
            }
            listViewThreads.Items.Clear();
            foreach (Order item in CurrentOrders.orders.order)
            {
                
                ListViewItem itemorder = new ListViewItem(item.token);
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.name));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.phone));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.email));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.link));
            
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.type));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.size));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.amount));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.copies));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.date));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.userid));
               
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.update));
                itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.more_info));
                //  itemLog.SubItems.Add(new ListViewItem.ListViewSubItem(itemLog, "sub item"));
                // itemLog.SubItems.Add(new ListViewItem.ListViewSubItem(itemLog, "sub item"));
                //  itemLog.SubItems.Add(new ListViewItem.ListViewSubItem(itemLog, "sub item"));
                //  itemLog.SubItems.Add(new ListViewItem.ListViewSubItem(itemLog, "sub item"));

                this.listViewThreads.Items.Add(itemorder);
                //itemLog.SubItems[1].Text =  item.Name;
                //itemLog.ImageIndex = 1;
                //itemLog.BackColor = Color.WhiteSmoke;
                //// initialize status to Connect
                //itemLog.SubItems[2].Text = "Connect";
                //itemLog.ForeColor = Color.Red;
                //itemLog.SubItems[3].Text = item.FullName;
                //itemLog.SubItems[4].Text = "";
                //itemLog.SubItems[5].Text = "";
                
            }
        }
        public void GetOrdersFromServer()
        {
            MakeRequest(OrdersUrl);
        
        
        }
        public void WebRequestinJson(string url, string postData)
        {
            StreamWriter requestWriter;

            var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
            if (webRequest != null)
            {
                webRequest.Method = "POST";
                webRequest.ServicePoint.Expect100Continue = false;
                webRequest.Timeout = 20000;

                webRequest.ContentType = "application/json";
                //POST the data.
                using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    //requestWriter.Write(postData);

                   
                }
            }
        }

        public void MakeRequest(string requestUrl)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                        response.StatusCode,
                        response.StatusDescription));
                    string[] searchResults;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string jsonresponse = reader.ReadToEnd();

                        CurrentOrders = JsonConvert.DeserializeObject<NagnagyOrders>(jsonresponse);
                    
                    }
                  
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
             //   return null;
            }
        }
        public void MakeRequest_update(string requestUrl)
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                        response.StatusCode,
                        response.StatusDescription));
                   

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                //   return null;
            }
        }
        private string DownloadOrder(Order ordertodownload)
        {
            string directory = string.Empty;
            MakeRequest(ordertodownload.link);
          //// 
           
            return directory;
        
        }
        private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
        {
            
                 lock (thisLock)
            {
            oredrToprint.Directory = DownloadPath + "\\" + oredrToprint.token;

            if (!Directory.Exists(oredrToprint.Directory))
                Directory.CreateDirectory(oredrToprint.Directory);
            foreach (Order itmord in CurrentOrders.orders.order)
            {
                if (oredrToprint.token == itmord.token)
                {
                   
                    foreach (Image item in itmord.images.image)
                    {
                        Uri linktodownload = new Uri(item.image_link);
                        WebClient cli = new WebClient();

                        cli.DownloadFileCompleted += new AsyncCompletedEventHandler(cli_DownloadFileCompleted);
                        cli.DownloadProgressChanged += new DownloadProgressChangedEventHandler(cli_DownloadProgressChanged);
                        string file_name = DownloadPath + "\\" + oredrToprint.token + "\\" + item.image_name;
                        //C:\nagd\2.zip_Order
                        oredrToprint.Directory = DownloadPath + "\\" + oredrToprint.token;
                        //cli.DownloadFileAsync(linktodownload, file_name);
                        cli.DownloadFile(linktodownload, file_name);

                    }
                
                }
            }
            
                 }
         
          //  cli.DownloadFile(linktodownload, DownloadPath+"\\"+ordertodownload.token+".zip");
           

     

            //
            // Boring....
            //
          //  Thread.Sleep(10000);

            /*argumentTest.OneValue = 6;
            argumentTest.TwoValue = 3;*/

            //
            // Now, return the values we generated in this method.
            // ... Use e.Result.
            //
         
        }

        void cli_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.progressBar1.BeginInvoke( 
    (MethodInvoker)delegate() { 
    progressBar1.Value = e.ProgressPercentage; 
    progressBar1.Refresh(); 
    //txtLogDetails.Text = message; 

    } );

          
        }
        
        void cli_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
          
           


        }

        void cli_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
           
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
        {
            progressBar1.Value = 0;

            
        }
        public void createOrderFolder(string orderNumber,string downlodedfile)
        {

            string fileName = string.Empty;
            string filelocation = DownloadPath + "\\" + orderNumber;
            fileName = Path.GetFileName(downlodedfile);
      
            if (!Directory.Exists(DownloadPath+"\\"+ orderNumber))
                Directory.CreateDirectory(DownloadPath + "\\" + orderNumber);
            //   Directory.Delete(destinationPath + destinationFolder, true);
          ReadOptions optionzip = new ReadOptions();
            //optionzip.StatusMessageWriter
            //string[] fileArray = Directory.GetFiles(sourcePath);
            using (ZipFile zip = ZipFile.Read(downlodedfile, optionzip))
            {
                // This call to ExtractAll() assumes:
                //   - none of the entries are password-protected.
                //   - want to extract all entries to current working directory
                //   - none of the files in the zip already exist in the directory;
                //     if they do, the method will throw.
                zip.ExtractAll(filelocation +"_Order");
            }
            
            

        }
        private void mainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewThreads.SelectedItems.Count > 0)
            {

                ListViewItem item = listViewThreads.SelectedItems[0];
                

                    oredrToprint = new Order();
                    oredrToprint.token = item.Text;
                    oredrToprint.name = item.SubItems[1].Text;
                    oredrToprint.phone = item.SubItems[2].Text;
                    oredrToprint.email = item.SubItems[3].Text;
                    oredrToprint.link = item.SubItems[4].Text;
                    oredrToprint.type = item.SubItems[5].Text;
                    oredrToprint.size = item.SubItems[6].Text;
                    oredrToprint.amount = item.SubItems[7].Text;
                    oredrToprint.copies = item.SubItems[8].Text;
                    oredrToprint.date = item.SubItems[9].Text;
                    oredrToprint.userid = item.SubItems[10].Text;
                    oredrToprint.update = item.SubItems[11].Text;
                    oredrToprint.more_info = item.SubItems[12].Text;

                    this.backgroundWorker1.RunWorkerAsync(oredrToprint.token);

                    while (this.backgroundWorker1.IsBusy)
                    {
                        progressBar1.Increment(1);
                        
                        // Keep UI messages moving, so the form remains  
                        // responsive during the asynchronous operation.
                        Application.DoEvents();
                    }

                    MakeRequest_update(oredrToprint.update);
                    GetOrdersFromServer();
                    FillOrderListUI();
                    ReportByIDAndProject repForm = new ReportByIDAndProject();
                    repForm.order = oredrToprint;
                    repForm.GenerateReportForOrder();
              
               /*    repForm.FormBorderStyle = FormBorderStyle.FixedToolWindow;

                  repForm.WindowState = FormWindowState.Normal;
                   repForm.ShowDialog();*/
             
                    /*
                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.phone));
                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.email));
                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.link));

                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.type));
                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.size));
                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.amount));
                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.date));
                    itemorder.SubItems.Add(new ListViewItem.ListViewSubItem(itemorder, item.update));
                    */
                   
                
               
            

            }
        }

        private void יציאהToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void הגדרותToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FormConfig configForm = new FormConfig();
            configForm.WindowState = FormWindowState.Normal;
            configForm.ShowDialog();
            this.Refresh();
        }

        private void ניהולהזמנותToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenApplication(OrdersManage);
        }
        public void OpenApplication(string myFavoritesPath)
        {
            // Start Internet Explorer. Defaults to the home page.
            Process.Start("IExplore.exe");

            // Display the contents of the favorites folder in the browser.
            Process.Start(myFavoritesPath);

        }

        private void תמיכהToolStripMenuItem_Click(object sender, EventArgs e)
        {
            about frm = new about();
            frm.ShowDialog();
        }

        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form1 frm = new Form1();
            frm.ShowDialog();
        }



       
    }
}
